package com.kwq.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kwq.common.Common;
import com.kwq.user.pojo.User;
import com.kwq.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "用户服务接口")
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @ApiOperation(value = "获取全部用户")
    @GetMapping("/selectAll")
    public Common selectAll() {
        try {
            List<User> users = userService.list();
            int total = userService.count();
            return new Common(200, "success", users, total);
        } catch (Exception e) {
            return new Common(500, e.getMessage());
        }

    }

    @ApiOperation(value = "通过id删除用户")
    @DeleteMapping("/deleteById")
    public Common deleteById(@PathVariable Integer id) {
        try {
            userService.removeById(id);
            return new Common(200, "success");
        } catch (Exception e) {
            return new Common(500, e.getMessage());
        }
    }

    @ApiOperation(value = "新增全部用户")
    @PostMapping("/saveAll")
    public Common saveAll(@RequestBody List<User> users) {
        try {
            boolean b = userService.saveBatch(users);
            int total = userService.count();
            return new Common(200, "success", b, total);
        } catch (Exception e) {
            return new Common(500, e.getMessage());
        }
    }

    @ApiOperation(value = "更新全部用户")
    @PostMapping("/updateAll")
    public Common updateAll(@RequestBody List<User> users) {
        try {
            userService.updateBatchById(users);
            return new Common(200, "success");
        } catch (Exception e) {
            return new Common(500, e.getMessage());
        }
    }

    @ApiOperation(value = "查看该用户是否存在")
    @PostMapping("/nameExit")
    public Common selectIfNameExit(String name) {
//        try {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("USER_NAME", name);
            User one = userService.getOne(queryWrapper);
            Boolean ifExit = false;
            if (one != null) {
                ifExit = true;
            }
            return new Common(200, "success", ifExit, 1);
//        } catch (Exception e) {
//            return new Common(500, e.getMessage());
//        }
    }
}